<template>
	<view class="chooseHospital">
		<view
			class="header"
			id="header"
			:style="{
				height: headerHeight + 'px',
				paddingTop: menuButtonInfo.top + 'px',
				borderBox: 'box-sizing',
				marginBottom: '10rpx',
				width: headerWidth + 'px',
				display: 'flex',
				alignItems: 'center',
				justifyContent: 'space-between',
				paddingLeft: '20rpx',
				paddingRight: '40rpx',
			}"
		>
			<u-icon
				name="arrow-left"
				color="#000"
				size="40"
				@click="handlerback"
			></u-icon>
			<u-field
				v-model="query"
				placeholder="请输入医院名称"
				icon="search"
				type="text"
				confirm-type="search"
				:border-bottom="false"
				@confirm="handlerConfirm"
				@focus="focus"
			/>
		</view>
		<view class="hotWord" v-show="searchFocus">
			<view class="title">
				<text style="color: #909399">历史搜索</text
				><u-icon
					name="trash-fill"
					color="#909399"
					size="28"
					@click="clearWordList"
				></u-icon>
			</view>
			<view class="wordList">
				<view
					v-for="(item, index) in wordList"
					:key="index"
					class="word"
					shape="circle"
					>{{ item }}</view
				>
			</view>
		</view>
		<view class="curHos" v-if="!searchFocus" id="curHos">
			<u-icon name="map" color="#5690FB" size="28"></u-icon>
			<text style="margin-right: 10rpx">当前医院:</text>
			<text>{{ curHos ? curHos : '请选择' }} </text>
		</view>
		<scroll-view
			v-show="!searchFocus"
			class="hostList"
			:style="{ height: listHeight }"
			scroll-y="true"
			:scrollTop="scrollTop"
			@scroll="handlerScroll"
		>
			<view class="list">
				<view
					class="list-line"
					v-for="item in hosList"
					:key="item.code"
					:id="'province' + item.code"
				>
					<view class="province">{{ item.province }}</view>
					<view
						class="hosinfo"
						v-for="(e, i) in item.children"
						:key="i"
						@click="chooseHos(e)"
					>
						<view class="icon"></view>
						<view class="info">
							<view class="name">{{ e.orgName }}</view>
							<view class="feature">特色科室: {{ e.deptName }}</view>
							<view class="distance"
								><u-icon name="map-fill" color="#5690FB" size="28"></u-icon
								><text>{{ e.distance }}</text></view
							>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="right-menu" v-if="!searchFocus && hosList.length">
			<view
				class="round"
				v-for="(item, index) in hosList"
				:class="{ 'round-active': item.code === curProvince }"
				:key="item.code"
				@click="handlerChangeProvince(item, index)"
				>{{ item.province }}</view
			>
		</view>
		<view class="safe" id="safe"></view>
		<u-toast ref="uToast" />
		<u-modal
			v-model="modalShow"
			:content="modalContent"
			@confirm="confirm"
		></u-modal>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import { getHospitalList, sysDataDictList } from '../../http/api'
export default {
	components: {},
	data() {
		return {
			modalShow: false,
			modalContent: '',
			curProvince: 0,
			pixelRatio: 0,
			windowHeight: 0,
			curHosHeight: 0,
			scrollTop: 0,
			isGetLocation: false, // * 是否获取到了坐标 false是获取到了 TRUE是没有获取到
			userLocation: {
				lat1: '',
				lng1: '',
			},
			provinceList: [],
			old: {
				scrollTop: 0,
			},
			hosList: [],
			menuButtonInfo: {},
			query: '',
			// curHos: '西安医院',
			searchFocus: false, //搜索框是否聚焦
			wordList: [],
		}
	},
	computed: {
		...mapState({
			curHos: state => state.curHos,
		}),
		headerHeight() {
			return this.menuButtonInfo.top + this.menuButtonInfo.height
		},
		headerWidth() {
			return this.menuButtonInfo.right - this.menuButtonInfo.width
		},
		listHeight() {
			return this.windowHeight - this.headerHeight - this.curHosHeight + 'px'
		},
	},
	methods: {
		...mapMutations(['changeCurHos']),
		chooseHos(item) {
			this.changeCurHos({
				name: item.orgName,
				id: item.id,
				orgCode: item.orgCode,
			})
			this.$router.switchTab({
				url: `/pages/index/index`,
			})
		},
		computedLat(d) {
			//根据经纬度判断距离
			return (d * Math.PI) / 180.0
		},
		computedDistance(lat2, lng2) {
			let res = ''
			if (!this.isGetLocation && lat2 && lng2) {
				let { lat1, lng1 } = this.userLocation
				let radLat1 = this.computedLat(lat1)
				let radLat2 = this.computedLat(lat2)
				let a = radLat1 - radLat2
				let b = this.computedLat(lng1) - this.computedLat(lng2)
				let s =
					2 *
					Math.asin(
						Math.sqrt(
							Math.pow(Math.sin(a / 2), 2) +
								Math.cos(radLat1) *
									Math.cos(radLat2) *
									Math.pow(Math.sin(b / 2), 2),
						),
					)
				s = s * 6378.137
				s = Math.round(s * 10000) / 10000
				s = s.toFixed(1) + ' km' //保留两位小数
				res = s
			}
			return res
		},
		computedHosList(list) {
			let pList = list.map(i => i.province)
			let res = []
			pList.forEach(i => {
				let samePList = list.filter(k => {
					if (k.province == i) {
						k.distance = this.computedDistance(k.lat, k.lng) || '未知距离'
						return k
					}
				})
				let pName = this.provinceList.find(j => j.value == i).display
				res.push({
					code: i,
					province: pName,
					children: samePList,
				})
			})
			return res
		},
		getHospitalList() {
			getHospitalList({ officeType: 1, orgNameOrInputCode: this.query }).then(
				({ data, head }) => {
					// console.log(data, head)
					if (head.code == 200) {
						this.hosList = this.computedHosList(data)
						// console.log(this.hosList)
						this.curProvince = this.hosList.length ? this.hosList[0].code : 0
					}
				},
			)
		},
		sysDataDictList() {
			sysDataDictList({ type: 'SP_PROVINCE_CODE' }).then(({ data, head }) => {
				// console.log(head, data)
				if (head.code == 200) {
					this.provinceList = data
					this.getHospitalList()
				}
			})
		},
		computedHeight() {
			let h = 0
			this.hosList.forEach(item => {
				// 获取节点信息的高度
				let view = uni.createSelectorQuery().select('#province' + item.code)
				view
					.fields(
						{
							size: true, // 是否返回节点尺寸
						},
						data => {
							// data是方法的回调函数，参数是指定的相关节点信息。
							// console.log(h)
							item.top = h // 顶部高度
							h += data.height
							// item.bottom = h // 底部高度
						},
					)
					.exec()
			})
		},
		handlerScroll(e) {
			// const deltaY = !!e.detail.deltaY
			this.old.scrollTop = e.detail.scrollTop
			let top = e.detail.scrollTop
			let index = this.hosList.findIndex(i => {
				return i.top > top && i.top != top
			})
			index = index - 1 < 0 ? 0 : index - 1
			if (!this.scrollLock) {
				this.curProvince = index
			}
			this.scrollLock = false
		},
		handlerChangeProvince(item) {
			this.scrollLock = true
			this.curProvince = item.code
			this.scrollTop = this.old.scrollTop
			this.$nextTick(() => {
				this.scrollTop = item.top
			})
		},
		focus() {
			this.searchFocus = true
		},
		handlerback() {
			if (this.searchFocus) {
				this.searchFocus = false
				this.query = ''
				this.getHospitalList()
			} else {
				uni.switchTab({ url: '/pages/index/index' })
			}
		},
		getButtonInfo() {
			this.menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		},
		handlerConfirm() {
			// this.$refs.uToast.show({
			// 	title: '成功',
			// 	type: 'success',
			// })
			if (this.wordList.length === 5) {
				this.wordList.push(this.query)
				this.wordList.splice(0, 1)
			} else {
				this.wordList.push(this.query)
			}
			uni.setStorageSync('hosWordList', JSON.stringify(this.wordList))
			this.getHospitalList()
			this.searchFocus = false
		},
		clearWordList() {
			this.wordList = []
			uni.setStorageSync('hosWordList', '')
		},
		getUserSetting() {
			let _this = this
			uni.getSetting({
				success(res) {
					const userLocation = res.authSetting['scope.userLocation']
					if (userLocation === false) {
						//检查用户是否授权了保存视频，没有则引导授权
						_this.modalContent = '为了获取附近医院，请您授权地理信息'
						_this.modalShow = true
					} else {
						//授权ok
						_this.getLocation()
					}
				},
			})
		},
		confirm() {
			this.modalShow = false
			this.openSetting()
		},
		openSetting() {
			let _this = this
			uni.openSetting({
				success(res) {
					// console.log(res, 66666)
					_this.getLocation()
				},
				fail(e) {
					console.log(e, 9999)
				},
			})
		},
		getLocation() {
			let _this = this
			uni.authorize({
				scope: 'scope.userLocation',
				success() {
					uni.getLocation({
						type: 'gcj02',
						success(res) {
							_this.userLocation.lat1 = res.latitude
							_this.userLocation.lng1 = res.longitude
							_this.initData()
						},
						fail(e) {
							console.log(e, 333)
							_this.initData(true)
						},
					})
				},
				fail(e) {
					console.log(e, 2222)
					_this.initData(true)
				},
			})
		},
		initData(bool) {
			this.isGetLocation = bool
			this.sysDataDictList()
		},
	},
	mounted() {
		// let _this = this
		const res = uni.getSystemInfoSync()
		this.pixelRatio = res.pixelRatio
		this.windowHeight = res.windowHeight
		// console.log(res)
		// console.log(this.listHeight, 111)
		const dom = uni.createSelectorQuery().in(this)
		dom
			.select('#curHos')
			.boundingClientRect(data => {
				this.curHosHeight = data.height
			})
			.exec()
		dom
			.select('#safe')
			.boundingClientRect(data => {
				this.curHosHeight =
					this.curHosHeight + (data.height ? data.height + 5 : 0)
				// console.log(data.height)
			})
			.exec()
		this.computedHeight()
	},
	onLoad() {
		this.getUserSetting()
		this.getButtonInfo()
		let res = uni.getStorageSync('hosWordList')
		this.wordList = res ? JSON.parse(res) : []
	},
}
</script>

<style lang="scss" >
.chooseHospital {
	position: relative;
	.header {
		.u-field {
			// width: 400rpx;
			margin-left: 40rpx;
			border: 1px solid #303133;
			padding: 3rpx;
			padding-left: 20rpx;
			border-radius: 28rpx;
		}
		.u-label {
			flex: 0 0 20rpx !important;
		}
	}
	.hotWord {
		box-sizing: border-box;
		padding: 20rpx 50rpx;
		.title {
			display: flex;
			justify-content: space-between;
			height: 30rpx;
			align-items: center;
		}
		.wordList {
			padding-top: 35rpx;
			.word {
				margin-right: 20rpx;
				margin-top: 10rpx;
				display: inline-block;
				line-height: 1;
				white-space: nowrap;
				cursor: pointer;
				background: #fff;
				border: 1rpx solid #dcdfe6;
				color: #909399;
				text-align: center;
				box-sizing: border-box;
				outline: none;
				transition: 0.1s;
				font-weight: 500;
				border-radius: 26rpx;
				padding: 10rpx 15rpx;
			}
		}
	}
	.curHos {
		height: 80rpx;
		display: flex;
		align-items: center;
		padding-left: 15rpx;
		box-sizing: border-box;
		color: #5690fb;
		border-bottom: 1px solid #dcdfe6;
		border-top: 1px solid #dcdfe6;
	}
	.hostList {
		overflow-y: auto;
		overflow-x: hidden;
		.list {
			.list-line {
				.province {
					height: 50rpx;
					background: #e4e7ed;
					color: #606266;
					display: flex;
					align-items: center;
					padding-left: 15rpx;
				}
				.hosinfo {
					padding: 15rpx;
					box-sizing: border-box;
					// height: 150rpx;
					display: flex;
					align-items: center;
					border-bottom: 1px solid #dcdfe6;
					.icon {
						height: 100rpx;
						width: 100rpx;
						border-radius: 50%;
						background-color: #cccc;
					}
					.info {
						margin-left: 15rpx;
						.name {
							font-weight: 700;
						}
						.feature {
							width: 300rpx;
							color: #909399;
						}
						.distance {
							color: #5690fb;
						}
					}
				}
			}
		}
	}
	.right-menu {
		position: fixed;
		top: 50%;
		right: 15rpx;
		transform: translateY(-50%);
		background: #fff;
		box-shadow: 0 0 5px 1px rgba(0, 0, 0, 0.1);
		font-size: 20rpx;
		padding: 15rpx;
		width: 90rpx;
		display: flex;
		flex-direction: column;
		// justify-content: center;
		align-items: center;
		border-radius: 45rpx;
		box-sizing: border-box;
		.round {
			// background: #ccc;
			margin-bottom: 25rpx;
			height: 70rpx;
			width: 70rpx;
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			transition: all 0.3s;
			&:last-child {
				margin-bottom: 0rpx;
			}
		}
		.round-active {
			background: #5690fb;
			color: #fff;
		}
	}
	.safe {
		height: 0;
		height: constant(safe-area-inset-bottom);
		height: env(safe-area-inset-bottom);
	}
}
</style>